package com.mayi.dao;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.mayi.utils.DBPoolConnection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 数据层
 * @Auther: yacong_liu
 * @Date: 2019/7/2
 * @version: 1.0
 */
public class DruidDao {

    /**
     * 功能描述: 获取实例<br>
     *
     * @Author: yacong_liu
     * @Date: 2019/7/3 11:47
     */
    public static DruidDao getInstance() {
        return new DruidDao();
    }

    /**
     * 功能描述: 执行sql<br>
     *
     * @Param: String sql
     * @Author: yacong_liu
     * @Date: 2019/7/3 10:33
     */
    public int excuteSQL(String sql) {
        DruidPooledConnection connection = null;
        PreparedStatement ps = null;
        try {
            connection = DBPoolConnection.getInstance().getConnection();
            ps = connection.prepareStatement(sql);
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBPoolConnection.release(connection, ps);
        }
        return -1;
    }

    /**
     * 功能描述: 查询<br>
     *
     * @Param: String sql
     * @Return: ResultSet
     * @Author: yacong_liu
     * @Date: 2019/7/3 11:57
     */
    public List<Map<String, Object>> excuteQuery(String sql) {
        DruidPooledConnection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            connection = DBPoolConnection.getInstance().getConnection();
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();

            return convertRStoList(resultSet);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBPoolConnection.release(connection, ps, resultSet);
        }

        return null;
    }

    private List<Map<String, Object>> convertRStoList(ResultSet rs) throws SQLException {
        if (null == rs) {
            return null;
        }
        List<Map<String, Object>> datas = new ArrayList<>();
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            Map<String, Object> rowData = new HashMap<>();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                rowData.put(metaData.getColumnName(i + 1), rs.getObject(i + 1));
            }
            datas.add(rowData);
        }

        return datas;
    }


}
